import React, { useState, useEffect, useRef } from "react";

// 添加全局样式以支持动画
if (typeof document !== 'undefined') {
  const style = document.createElement('style');
  style.textContent = `
    @keyframes pulse {
      0% {
        opacity: 0.8;
      }
      50% {
        opacity: 1;
      }
      100% {
        opacity: 0.8;
      }
    }
    
    @keyframes fadeIn {
      from {
        opacity: 0;
        transform: translateY(-20px);
      }
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }
  `;
  document.head.appendChild(style);
}

// 极简版登录页面组件
const LoginPage: React.FC = () => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [captcha, setCaptcha] = useState('');
  const [captchaKey, setCaptchaKey] = useState('');
  const [captchaImage, setCaptchaImage] = useState('');
  const [loading, setLoading] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [showCaptchaModal, setShowCaptchaModal] = useState(false);
  const [rememberMe, setRememberMe] = useState(false);
  const countdownTimerRef = useRef<NodeJS.Timeout | null>(null);

  // 忘记密码相关状态
  const [showForgotPassword, setShowForgotPassword] = useState(false);
  const [phone, setPhone] = useState('');
  const [smsCode, setSmsCode] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [smsCountdown, setSmsCountdown] = useState(0);
  const [step, setStep] = useState(1); // 1: 输入手机号, 2: 输入验证码, 3: 设置新密码
  const [forgotCaptchaKey, setForgotCaptchaKey] = useState('');
  const [forgotCaptchaImage, setForgotCaptchaImage] = useState('');
  const [forgotCaptcha, setForgotCaptcha] = useState('');
  const [forgotCaptchaText, setForgotCaptchaText] = useState('');
  const [showForgotCaptchaModal, setShowForgotCaptchaModal] = useState(false);
  const smsCountdownTimerRef = useRef<NodeJS.Timeout | null>(null);
  
  // 注册相关状态
  const [showRegister, setShowRegister] = useState(false);
  const [registerUsername, setRegisterUsername] = useState('');
  const [registerPassword, setRegisterPassword] = useState('');
  const [registerConfirmPassword, setRegisterConfirmPassword] = useState('');
  const [registerPhone, setRegisterPhone] = useState('');
  const [registerSmsCode, setRegisterSmsCode] = useState('');
  const [registerCaptcha, setRegisterCaptcha] = useState('');
  const [registerCaptchaKey, setRegisterCaptchaKey] = useState('');
  const [registerCaptchaImage, setRegisterCaptchaImage] = useState('');
  const [registerCountdown, setRegisterCountdown] = useState(0);
  const [registerSmsCountdown, setRegisterSmsCountdown] = useState(0);
  const [registerShowCaptchaModal, setRegisterShowCaptchaModal] = useState(false);
  const [registerStep, setRegisterStep] = useState(1); // 1: 基本信息, 2: 手机验证
  const registerCountdownTimerRef = useRef<NodeJS.Timeout | null>(null);
  const registerSmsCountdownTimerRef = useRef<NodeJS.Timeout | null>(null);
  const [captchaText, setCaptchaText] = useState('');
  const [registerCaptchaText, setRegisterCaptchaText] = useState('');
  const [mockUsers, setMockUsers] = useState<any[]>([
    { username: 'admin', password: '123456', role: 'admin', name: '管理员' },
    { username: 'test', password: '123456', role: 'user', name: '测试用户' }
  ]);

  // 内部API请求函数，能够访问组件状态
  const fetchApi = async (url: string, options: RequestInit = {}) => {
    // 验证码API响应
    if (url === '/api/auth/captcha') {
      const mockCaptchaKey = Math.random().toString(36).substring(2, 15);
      const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
      let mockCaptchaText = '';
      for (let i = 0; i < 6; i++) {
        mockCaptchaText += characters.charAt(Math.floor(Math.random() * characters.length));
      }
      return {
        success: true,
        data: {
          captchaKey: mockCaptchaKey,
          text: mockCaptchaText
        },
        msg: '获取验证码成功'
      };
    }
    
    // 短信验证码API响应
    if (url === '/api/auth/sms-code' && options.method === 'POST') {
      return {
        success: true,
        msg: '短信验证码已发送，请注意查收（测试环境验证码为123456）'
      };
    }
    
    // 重置密码API响应
    if (url === '/api/auth/reset-password' && options.method === 'POST') {
      // 在模拟环境中更新mockUsers中的密码
      const body = options.body ? JSON.parse(options.body.toString()) : {};
      setMockUsers(prevUsers => 
        prevUsers.map(user => 
          user.phone === body.phone 
            ? { ...user, password: body.newPassword }
            : user
        )
      );
      return {
        success: true,
        msg: '密码重置成功，请使用新密码登录'
      };
    }
    
    // 注册API响应 - 现在会将新用户添加到mockUsers状态中
    if (url === '/api/auth/register' && options.method === 'POST') {
      const body = options.body ? JSON.parse(options.body.toString()) : {};
      
      // 检查用户名是否已存在
      const existingUser = mockUsers.find(user => user.username === body.username);
      if (existingUser) {
        return {
          success: false,
          msg: '用户名已存在'
        };
      }
      
      // 添加新用户到mockUsers状态
      const newUser = {
        username: body.username,
        password: body.password,
        phone: body.phone,
        role: 'user',
        name: body.username // 默认使用用户名作为显示名称
      };
      
      setMockUsers(prevUsers => [...prevUsers, newUser]);
      
      return {
        success: true,
        msg: '注册成功！'
      };
    }
    
    // 登录API响应 - 现在会检查mockUsers状态中的所有用户
    if (url === '/api/auth/login' && options.method === 'POST') {
      const body = options.body ? JSON.parse(options.body.toString()) : {};
      
      // 检查所有mock用户
      const user = mockUsers.find(u => u.username === body.username && u.password === body.password);
      
      if (user) {
        return {
          success: true,
          data: {
            token: 'mock_token_' + Date.now(),
            role: user.role || 'user',
            name: user.name || user.username
          },
          msg: '登录成功'
        };
      } else {
        return {
          success: false,
          msg: '用户名或密码错误'
        };
      }
    }
    
    // 真实API请求
    try {
      const response = await fetch(url, {
        ...options,
        headers: {
          'Content-Type': 'application/json',
          ...options.headers,
        },
      });
      const data = await response.json();
      return data;
    } catch (error) {
      console.error('API请求失败:', error);
      alert('网络错误，请稍后重试');
      return null;
    }
  };

  // 生成登录验证码
  const generateCaptcha = async () => {
    try {
      const response = await fetchApi('/api/auth/captcha');
      if (response && response.success) {
        setCaptchaKey(response.data.captchaKey);
        setCaptchaText(response.data.text || '');
        setShowCaptchaModal(true);
        setCountdown(60);
      } else {
        alert(response?.msg || '获取验证码失败');
      }
    } catch (error) {
      console.error('获取验证码失败:', error);
    }
  };

  // 生成忘记密码验证码
  const generateForgotCaptcha = async () => {
    try {
      const response = await fetchApi('/api/auth/captcha');
      if (response && response.success) {
        setForgotCaptchaKey(response.data.captchaKey);
        setForgotCaptchaText(response.data.text || '');
        setShowForgotCaptchaModal(true);
      } else {
        alert(response?.msg || '获取验证码失败');
      }
    } catch (error) {
      console.error('获取验证码失败:', error);
    }
  };

  // 发送忘记密码短信验证码
  const sendSmsCode = async () => {
    // 验证手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(phone)) {
      alert('请输入正确的手机号');
      return;
    }

    try {
      const response = await fetchApi('/api/auth/sms-code', {
        method: 'POST',
        body: JSON.stringify({
          phone,
          captchaKey: forgotCaptchaKey,
          captcha: forgotCaptcha
        })
      });

      if (response && response.success) {
        alert(response.msg || '短信验证码发送成功');
        setSmsCountdown(60);
        setStep(2);
      } else {
        alert(response?.msg || '发送验证码失败');
        generateForgotCaptcha();
      }
    } catch (error) {
      console.error('发送验证码失败:', error);
      alert('发送验证码失败，请稍后重试');
    }
  };

  // 验证短信验证码
  const verifySmsCode = () => {
    if (smsCode.length !== 6) {
      alert('请输入6位短信验证码');
      return;
    }
    
    // 在实际应用中，这里应该调用API验证短信验证码
    // 模拟环境中，我们直接跳转到设置新密码步骤
    setStep(3);
  };

  // 重置密码
  const resetPassword = async () => {
    if (newPassword.length < 6) {
      alert('密码长度不能少于6位');
      return;
    }
    
    if (newPassword !== confirmPassword) {
      alert('两次输入的密码不一致');
      return;
    }
    
    try {
      const response = await fetchApi('/api/auth/reset-password', {
        method: 'POST',
        body: JSON.stringify({
          phone,
          smsCode,
          newPassword
        })
      });
      
      if (response && response.success) {
        alert(response.msg || '密码重置成功');
        resetForgotPasswordState();
      } else {
        alert(response?.msg || '密码重置失败');
      }
    } catch (error) {
      console.error('密码重置失败:', error);
      alert('密码重置失败，请稍后重试');
    }
  };

  // 重置忘记密码状态
  const resetForgotPasswordState = () => {
    setShowForgotPassword(false);
    setPhone('');
    setSmsCode('');
    setNewPassword('');
    setConfirmPassword('');
    setStep(1);
    if (smsCountdownTimerRef.current) {
      clearInterval(smsCountdownTimerRef.current);
      smsCountdownTimerRef.current = null;
    }
    setSmsCountdown(0);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
  
    try {
      // 直接调用真实的后端API（绕过 mock）
      const response = await fetch('http://localhost:3000/api/v1/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username,
          password,
          captchaKey,
          captcha: captcha.toUpperCase()
        })
      });

      const data = await response.json();
  
      if (data && data.success) {
        // 根据记住密码状态保存凭据
        if (rememberMe) {
          localStorage.setItem('remembered_username', username);
          localStorage.setItem('remembered_password', password);
        } else {
          localStorage.removeItem('remembered_username');
          localStorage.removeItem('remembered_password');
        }
        
        // 保存用户信息到本地存储
        localStorage.setItem('userRole', data.data.role);
        localStorage.setItem('userName', data.data.name || username);
        localStorage.setItem('userEmail', data.data.email || '');
        localStorage.setItem('admin_token', data.data.token);
        
        alert('登录成功！');
        
        // 登录成功，跳转到首页
        setTimeout(() => {
          window.location.href = '/';
        }, 1000);
      } else {
        alert(data?.message || '用户名或密码错误');
        generateCaptcha();
      }
    } catch (error) {
      console.error('登录失败:', error);
      alert('登录失败，请稍后重试');
      generateCaptcha();
    } finally {
      setLoading(false);
    }
  };

  // 处理忘记密码
  const handleForgotPassword = () => {
    setShowForgotPassword(true);
  };

  // 生成注册验证码
  // 修改生成注册验证码函数，调用mock API接口
  const generateRegisterCaptcha = async () => {
    try {
      const response = await fetchApi('/api/auth/captcha');
      if (response && response.success) {
        setRegisterCaptchaKey(response.data.captchaKey);
        setRegisterCaptchaText(response.data.text || '');
        setRegisterShowCaptchaModal(true);
        setRegisterCountdown(60);
      } else {
        alert(response?.msg || '获取验证码失败');
      }
    } catch (error) {
      console.error('获取验证码失败:', error);
    }
  };

  // 模拟发送注册短信验证码
  const sendRegisterSmsCode = async () => {
    // 验证手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(registerPhone)) {
      alert('请输入正确的手机号');
      return;
    }
  
    try {
      const response = await fetchApi('/api/auth/sms-code', {
        method: 'POST',
        body: JSON.stringify({
          phone: registerPhone,
          captchaKey: registerCaptchaKey,
          captcha: registerCaptcha
        })
      });
  
      if (response && response.success) {
        alert(response.msg || '短信验证码发送成功');
        setRegisterSmsCountdown(60);
        setRegisterStep(2);
      } else {
        alert(response?.msg || '发送验证码失败');
        generateRegisterCaptcha();
      }
    } catch (error) {
      console.error('发送验证码失败:', error);
      alert('发送验证码失败，请稍后重试');
    }
  };

  // 处理注册
  const handleRegister = () => {
    setShowRegister(true);
  };

  // 验证注册信息并创建用户
  const registerUser = async () => {
    try {
      const response = await fetchApi('/api/auth/register', {
        method: 'POST',
        body: JSON.stringify({
          username: registerUsername,
          password: registerPassword,
          phone: registerPhone,
          smsCode: registerSmsCode
        })
      });
  
      if (response && response.success) {
        alert(response.msg || '注册成功！');
        
        // 先自动填充用户名，然后再重置注册状态
        setUsername(registerUsername);
        
        // 重置注册状态并返回登录页
        resetRegisterState();
      } else {
        alert(response?.msg || '注册失败');
      }
    } catch (error) {
      console.error('注册失败:', error);
      alert('注册失败，请稍后重试');
    }
  };

  // 重置注册相关状态
  const resetRegisterState = () => {
    setShowRegister(false);
    setRegisterUsername('');
    setRegisterPassword('');
    setRegisterConfirmPassword('');
    setRegisterPhone('');
    setRegisterSmsCode('');
    setRegisterCaptcha('');
    setRegisterStep(1);
    if (registerCountdownTimerRef.current) {
      clearInterval(registerCountdownTimerRef.current);
      registerCountdownTimerRef.current = null;
    }
    if (registerSmsCountdownTimerRef.current) {
      clearInterval(registerSmsCountdownTimerRef.current);
      registerSmsCountdownTimerRef.current = null;
    }
    setRegisterCountdown(0);
    setRegisterSmsCountdown(0);
  };

  // 验证码倒计时效果
  useEffect(() => {
    if (countdown > 0) {
      countdownTimerRef.current = setInterval(() => {
        setCountdown((prevCount) => {
          if (prevCount <= 1) {
            if (countdownTimerRef.current) {
              clearInterval(countdownTimerRef.current);
              countdownTimerRef.current = null;
            }
            return 0;
          }
          return prevCount - 1;
        });
      }, 1000);
    }

    return () => {
      if (countdownTimerRef.current) {
        clearInterval(countdownTimerRef.current);
        countdownTimerRef.current = null;
      }
    };
  }, [countdown]);

  // 忘记密码短信验证码倒计时
  useEffect(() => {
    if (smsCountdown > 0) {
      smsCountdownTimerRef.current = setInterval(() => {
        setSmsCountdown((prevCount) => {
          if (prevCount <= 1) {
            if (smsCountdownTimerRef.current) {
              clearInterval(smsCountdownTimerRef.current);
              smsCountdownTimerRef.current = null;
            }
            return 0;
          }
          return prevCount - 1;
        });
      }, 1000);
    }

    return () => {
      if (smsCountdownTimerRef.current) {
        clearInterval(smsCountdownTimerRef.current);
        smsCountdownTimerRef.current = null;
      }
    };
  }, [smsCountdown]);

  // 注册验证码倒计时
  useEffect(() => {
    if (registerCountdown > 0) {
      registerCountdownTimerRef.current = setInterval(() => {
        setRegisterCountdown((prevCount) => {
          if (prevCount <= 1) {
            if (registerCountdownTimerRef.current) {
              clearInterval(registerCountdownTimerRef.current);
              registerCountdownTimerRef.current = null;
            }
            return 0;
          }
          return prevCount - 1;
        });
      }, 1000);
    }

    return () => {
      if (registerCountdownTimerRef.current) {
        clearInterval(registerCountdownTimerRef.current);
        registerCountdownTimerRef.current = null;
      }
    };
  }, [registerCountdown]);

  // 注册短信验证码倒计时
  useEffect(() => {
    if (registerSmsCountdown > 0) {
      registerSmsCountdownTimerRef.current = setInterval(() => {
        setRegisterSmsCountdown((prevCount) => {
          if (prevCount <= 1) {
            if (registerSmsCountdownTimerRef.current) {
              clearInterval(registerSmsCountdownTimerRef.current);
              registerSmsCountdownTimerRef.current = null;
            }
            return 0;
          }
          return prevCount - 1;
        });
      }, 1000);
    }

    return () => {
      if (registerSmsCountdownTimerRef.current) {
        clearInterval(registerSmsCountdownTimerRef.current);
        registerSmsCountdownTimerRef.current = null;
      }
    };
  }, [registerSmsCountdown]);

  // 检查记住密码状态
  useEffect(() => {
    const rememberedUsername = localStorage.getItem('remembered_username');
    const rememberedPassword = localStorage.getItem('remembered_password');
    
    if (rememberedUsername && rememberedPassword) {
      setUsername(rememberedUsername);
      setPassword(rememberedPassword);
      setRememberMe(true);
    }
  }, []);

  // 渲染注册表单
  const renderRegisterForm = () => {
    return (
      <div>
        <h2 style={{ textAlign: 'center', marginBottom: '30px', color: '#2d6aff' }}>账号注册</h2>
        
        {registerStep === 1 && (
          <div>
            <div style={{ marginBottom: '20px' }}>
              <label style={{ display: 'block', marginBottom: '8px', color: '#666' }}>用户名</label>
              <input
                type="text"
                value={registerUsername}
                onChange={(e) => setRegisterUsername(e.target.value)}
                placeholder="请设置用户名"
                style={{
                  width: '100%',
                  padding: '8px 12px',
                  border: '1px solid #d9d9d9',
                  borderRadius: '4px',
                  fontSize: '14px'
                }}
                required
              />
            </div>
            
            <div style={{ marginBottom: '20px' }}>
              <label style={{ display: 'block', marginBottom: '8px', color: '#666' }}>密码</label>
              <input
                type="password"
                value={registerPassword}
                onChange={(e) => setRegisterPassword(e.target.value)}
                placeholder="请设置密码（不少于6位）"
                style={{
                  width: '100%',
                  padding: '8px 12px',
                  border: '1px solid #d9d9d9',
                  borderRadius: '4px',
                  fontSize: '14px'
                }}
                required
              />
            </div>
            
            <div style={{ marginBottom: '20px' }}>
              <label style={{ display: 'block', marginBottom: '8px', color: '#666' }}>确认密码</label>
              <input
                type="password"
                value={registerConfirmPassword}
                onChange={(e) => setRegisterConfirmPassword(e.target.value)}
                placeholder="请再次输入密码"
                style={{
                  width: '100%',
                  padding: '8px 12px',
                  border: '1px solid #d9d9d9',
                  borderRadius: '4px',
                  fontSize: '14px'
                }}
                required
              />
            </div>
            
            <div style={{ marginBottom: '20px' }}>
              <label style={{ display: 'block', marginBottom: '8px', color: '#666' }}>手机号</label>
              <input
                type="tel"
                value={registerPhone}
                onChange={(e) => setRegisterPhone(e.target.value)}
                placeholder="请输入手机号"
                style={{
                  width: '100%',
                  padding: '8px 12px',
                  border: '1px solid #d9d9d9',
                  borderRadius: '4px',
                  fontSize: '14px'
                }}
                required
              />
            </div>
            
            <div style={{ marginBottom: '20px' }}>
              <label style={{ display: 'block', marginBottom: '8px', color: '#666' }}>验证码</label>
              <div style={{ display: 'flex', gap: '10px' }}>
                <input
                  type="text"
                  value={registerCaptcha}
                  onChange={(e) => setRegisterCaptcha(e.target.value)}
                  placeholder="请输入验证码"
                  style={{
                    flex: 1,
                    padding: '8px 12px',
                    border: '1px solid #d9d9d9',
                    borderRadius: '4px',
                    fontSize: '14px'
                  }}
                  required
                />
                <button
                  type="button"
                  onClick={registerCountdown === 0 ? generateRegisterCaptcha : undefined}
                  disabled={registerCountdown > 0}
                  style={{
                    padding: '8px 16px',
                    backgroundColor: registerCountdown === 0 ? '#2d6aff' : '#f5f5f5',
                    color: registerCountdown === 0 ? 'white' : '#666',
                    borderRadius: '4px',
                    cursor: registerCountdown === 0 ? 'pointer' : 'not-allowed',
                    border: 'none',
                    minWidth: '120px',
                    textAlign: 'center',
                    userSelect: 'none',
                    opacity: registerCountdown > 0 ? 0.6 : 1,
                    fontSize: '14px'
                  }}
                >
                  {registerCountdown > 0 ? `${registerCountdown}s后重新获取` : '获取验证码'}
                </button>
              </div>
            </div>
            
            <button
              type="button"
              onClick={() => {
                // 验证密码长度
                if (registerPassword.length < 6) {
                  alert('密码长度不能少于6位');
                  return;
                }
                
                // 验证两次输入的密码是否一致
                if (registerPassword !== registerConfirmPassword) {
                  alert('两次输入的密码不一致');
                  return;
                }
                
                // 验证用户名
                if (registerUsername.trim() === '') {
                  alert('请输入用户名');
                  return;
                }
                
                // 验证手机号
                const phoneRegex = /^1[3-9]\d{9}$/;
                if (!phoneRegex.test(registerPhone)) {
                  alert('请输入正确的手机号');
                  return;
                }
                
                // 验证验证码
                if (registerCaptcha.toUpperCase() !== registerCaptchaText) {
                  alert('验证码错误');
                  generateRegisterCaptcha();
                  return;
                }
                
                sendRegisterSmsCode();
              }}
              style={{
                width: '100%',
                padding: '12px',
                backgroundColor: '#2d6aff',
                color: 'white',
                border: 'none',
                borderRadius: '8px',
                fontSize: '16px',
                fontWeight: '600',
                cursor: 'pointer',
                transition: 'all 0.3s ease',
                marginTop: '10px'
              }}
            >
              下一步
            </button>
          </div>
        )}
        
        {registerStep === 2 && (
          <div>
            <div style={{ marginBottom: '20px' }}>
              <label style={{ display: 'block', marginBottom: '8px', color: '#666' }}>短信验证码</label>
              <div style={{ display: 'flex', gap: '10px' }}>
                <input
                  type="text"
                  value={registerSmsCode}
                  onChange={(e) => setRegisterSmsCode(e.target.value)}
                  placeholder="请输入短信验证码"
                  style={{
                    flex: 1,
                    padding: '8px 12px',
                    border: '1px solid #d9d9d9',
                    borderRadius: '4px',
                    fontSize: '14px'
                  }}
                  required
                />
                <button
                  type="button"
                  onClick={sendRegisterSmsCode}
                  disabled={registerSmsCountdown > 0}
                  style={{
                    padding: '8px 16px',
                    backgroundColor: registerSmsCountdown === 0 ? '#2d6aff' : '#f5f5f5',
                    color: registerSmsCountdown === 0 ? 'white' : '#666',
                    borderRadius: '4px',
                    cursor: registerSmsCountdown === 0 ? 'pointer' : 'not-allowed',
                    border: 'none',
                    minWidth: '120px',
                    textAlign: 'center',
                    userSelect: 'none',
                    opacity: registerSmsCountdown > 0 ? 0.6 : 1,
                    fontSize: '14px'
                  }}
                >
                  {registerSmsCountdown > 0 ? `${registerSmsCountdown}s后重新获取` : '重新获取'}
                </button>
              </div>
            </div>
            
            <div style={{ display: 'flex', gap: '10px', marginTop: '10px' }}>
              <button
                type="button"
                onClick={() => setRegisterStep(1)}
                style={{
                  flex: 1,
                  padding: '12px',
                  backgroundColor: '#f5f5f5',
                  color: '#666',
                  border: '1px solid #d9d9d9',
                  borderRadius: '8px',
                  fontSize: '16px',
                  fontWeight: '600',
                  cursor: 'pointer',
                  transition: 'all 0.3s ease'
                }}
              >
                返回
              </button>
              <button
                type="button"
                onClick={registerUser}
                style={{
                  flex: 1,
                  padding: '12px',
                  backgroundColor: '#2d6aff',
                  color: 'white',
                  border: 'none',
                  borderRadius: '8px',
                  fontSize: '16px',
                  fontWeight: '600',
                  cursor: 'pointer',
                  transition: 'all 0.3s ease'
                }}
              >
                完成注册
              </button>
            </div>
          </div>
        )}
        
        <div style={{ marginTop: '20px', textAlign: 'center' }}>
          <button
            type="button"
            onClick={resetRegisterState}
            style={{
              background: 'none',
              border: 'none',
              color: '#2d6aff',
              fontSize: '14px',
              cursor: 'pointer',
              padding: '0',
              textDecoration: 'underline'
            }}
          >
            返回登录
          </button>
        </div>
      </div>
    );
  };

  // 渲染忘记密码表单
  const renderForgotPasswordForm = () => {
    return (
      <div>
        <h2 style={{ textAlign: 'center', marginBottom: '30px', color: '#2d6aff' }}>忘记密码</h2>
        
        {step === 1 && (
          <div>
            <div style={{ marginBottom: '20px' }}>
              <label style={{ display: 'block', marginBottom: '8px', color: '#666' }}>手机号</label>
              <input
                type="tel"
                value={phone}
                onChange={(e) => setPhone(e.target.value)}
                placeholder="请输入注册手机号"
                style={{
                  width: '100%',
                  padding: '8px 12px',
                  border: '1px solid #d9d9d9',
                  borderRadius: '4px',
                  fontSize: '14px'
                }}
                required
              />
            </div>
            
            <button
              type="button"
              onClick={sendSmsCode}
              style={{
                width: '100%',
                padding: '12px',
                backgroundColor: '#2d6aff',
                color: 'white',
                border: 'none',
                borderRadius: '8px',
                fontSize: '16px',
                fontWeight: '600',
                cursor: 'pointer',
                transition: 'all 0.3s ease',
                marginTop: '10px'
              }}
            >
              发送验证码
            </button>
          </div>
        )}
        
        {step === 2 && (
          <div>
            <div style={{ marginBottom: '20px' }}>
              <label style={{ display: 'block', marginBottom: '8px', color: '#666' }}>短信验证码</label>
              <div style={{ display: 'flex', gap: '10px' }}>
                <input
                  type="text"
                  value={smsCode}
                  onChange={(e) => setSmsCode(e.target.value)}
                  placeholder="请输入验证码"
                  style={{
                    flex: 1,
                    padding: '8px 12px',
                    border: '1px solid #d9d9d9',
                    borderRadius: '4px',
                    fontSize: '14px'
                  }}
                  required
                />
                <button
                  type="button"
                  onClick={sendSmsCode}
                  disabled={smsCountdown > 0}
                  style={{
                    padding: '8px 16px',
                    backgroundColor: smsCountdown === 0 ? '#2d6aff' : '#f5f5f5',
                    color: smsCountdown === 0 ? 'white' : '#666',
                    borderRadius: '4px',
                    cursor: smsCountdown === 0 ? 'pointer' : 'not-allowed',
                    border: 'none',
                    minWidth: '120px',
                    textAlign: 'center',
                    userSelect: 'none',
                    opacity: smsCountdown > 0 ? 0.6 : 1,
                    fontSize: '14px'
                  }}
                >
                  {smsCountdown > 0 ? `${smsCountdown}s后重新获取` : '重新获取'}
                </button>
              </div>
            </div>
            
            <div style={{ display: 'flex', gap: '10px', marginTop: '10px' }}>
              <button
                type="button"
                onClick={() => setStep(1)}
                style={{
                  flex: 1,
                  padding: '12px',
                  backgroundColor: '#f5f5f5',
                  color: '#666',
                  border: '1px solid #d9d9d9',
                  borderRadius: '8px',
                  fontSize: '16px',
                  fontWeight: '600',
                  cursor: 'pointer',
                  transition: 'all 0.3s ease'
                }}
              >
                返回
              </button>
              <button
                type="button"
                onClick={verifySmsCode}
                style={{
                  flex: 1,
                  padding: '12px',
                  backgroundColor: '#2d6aff',
                  color: 'white',
                  border: 'none',
                  borderRadius: '8px',
                  fontSize: '16px',
                  fontWeight: '600',
                  cursor: 'pointer',
                  transition: 'all 0.3s ease'
                }}
              >
                验证
              </button>
            </div>
          </div>
        )}
        
        {step === 3 && (
          <div>
            <div style={{ marginBottom: '20px' }}>
              <label style={{ display: 'block', marginBottom: '8px', color: '#666' }}>新密码</label>
              <input
                type="password"
                value={newPassword}
                onChange={(e) => setNewPassword(e.target.value)}
                placeholder="请输入新密码"
                style={{
                  width: '100%',
                  padding: '8px 12px',
                  border: '1px solid #d9d9d9',
                  borderRadius: '4px',
                  fontSize: '14px'
                }}
                required
              />
            </div>
            
            <div style={{ marginBottom: '20px' }}>
              <label style={{ display: 'block', marginBottom: '8px', color: '#666' }}>确认新密码</label>
              <input
                type="password"
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
                placeholder="请再次输入新密码"
                style={{
                  width: '100%',
                  padding: '8px 12px',
                  border: '1px solid #d9d9d9',
                  borderRadius: '4px',
                  fontSize: '14px'
                }}
                required
              />
            </div>
            
            <div style={{ display: 'flex', gap: '10px', marginTop: '10px' }}>
              <button
                type="button"
                onClick={() => setStep(2)}
                style={{
                  flex: 1,
                  padding: '12px',
                  backgroundColor: '#f5f5f5',
                  color: '#666',
                  border: '1px solid #d9d9d9',
                  borderRadius: '8px',
                  fontSize: '16px',
                  fontWeight: '600',
                  cursor: 'pointer',
                  transition: 'all 0.3s ease'
                }}
              >
                返回
              </button>
              <button
                type="button"
                onClick={resetPassword}
                style={{
                  flex: 1,
                  padding: '12px',
                  backgroundColor: '#2d6aff',
                  color: 'white',
                  border: 'none',
                  borderRadius: '8px',
                  fontSize: '16px',
                  fontWeight: '600',
                  cursor: 'pointer',
                  transition: 'all 0.3s ease'
                }}
              >
                确认重置
              </button>
            </div>
          </div>
        )}
        
        <div style={{ marginTop: '20px', textAlign: 'center' }}>
          <button
            type="button"
            onClick={resetForgotPasswordState}
            style={{
              background: 'none',
              border: 'none',
              color: '#2d6aff',
              fontSize: '14px',
              cursor: 'pointer',
              padding: '0',
              textDecoration: 'underline'
            }}
          >
            返回登录
          </button>
        </div>
      </div>
    );
  };

  return (
    <div style={{
      minHeight: '100vh',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      backgroundColor: '#0a1929',
      padding: '20px',
      position: 'relative',
      overflow: 'hidden'
    }}>
      {/* 背景主渐变色遮罩 */}
      <div style={{
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        background: 'radial-gradient(circle at 50% 50%, rgba(45, 106, 255, 0.15) 0%, rgba(76, 175, 80, 0.05) 40%, rgba(0, 0, 0, 0) 70%)',
        zIndex: 0,
        animation: 'pulse 15s infinite ease-in-out'
      }}></div>
      
      {/* 装饰性网格遮罩 */}
      <div style={{
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundImage: 'linear-gradient(rgba(255, 255, 255, 0.02) 1px, transparent 1px), linear-gradient(90deg, rgba(255, 255, 255, 0.02) 1px, transparent 1px)',
        backgroundSize: '30px 30px',
        zIndex: 0
      }}></div>
      
      {/* 底部装饰性渐变 */}
      <div style={{
        position: 'absolute',
        bottom: 0,
        left: 0,
        right: 0,
        height: '30%',
        background: 'linear-gradient(180deg, rgba(45, 106, 255, 0) 0%, rgba(45, 106, 255, 0.05) 100%)',
        zIndex: 0
      }}></div>
      
      <div style={{
        width: '100%',
        maxWidth: '400px',
        backgroundColor: 'rgba(255, 255, 255, 0.98)',
        padding: '40px',
        borderRadius: '12px',
        boxShadow: '0 10px 40px rgba(21, 101, 192, 0.15), 0 0 0 1px rgba(255, 255, 255, 0.1)',
        backdropFilter: 'blur(20px)',
        border: '1px solid rgba(255, 255, 255, 0.12)',
        position: 'relative',
        zIndex: 1
        }}>
          {showRegister ? (
            renderRegisterForm()
          ) : showForgotPassword ? (
            renderForgotPasswordForm()
          ) : (
            <>
              <h2 style={{ textAlign: 'center', marginBottom: '30px', color: '#2d6aff' }}>管理系统登录</h2>
              
              <form onSubmit={handleSubmit}>
              <div style={{ marginBottom: '20px' }}>
                <label style={{ display: 'block', marginBottom: '8px', color: '#666' }}>用户名</label>
                <input
                  type="text"
                  value={username}
                  onChange={(e) => setUsername(e.target.value)}
                  placeholder="请输入用户名"
                  style={{
                    width: '100%',
                    padding: '8px 12px',
                    border: '1px solid #d9d9d9',
                    borderRadius: '4px',
                    fontSize: '14px'
                  }}
                  required
                />
              </div>

              <div style={{ marginBottom: '20px' }}>
                <label style={{ display: 'block', marginBottom: '8px', color: '#666' }}>密码</label>
                <input
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="请输入密码"
                  style={{
                    width: '100%',
                    padding: '8px 12px',
                    border: '1px solid #d9d9d9',
                    borderRadius: '4px',
                    fontSize: '14px'
                  }}
                  required
                />
              </div>

              <div style={{ marginBottom: '20px' }}>
                <label style={{ display: 'block', marginBottom: '8px', color: '#666' }}>验证码</label>
                <div style={{ display: 'flex', gap: '10px' }}>
                  <input
                    type="text"
                    value={captcha}
                    onChange={(e) => setCaptcha(e.target.value)}
                    placeholder="请输入验证码"
                    style={{
                      flex: 1,
                      padding: '8px 12px',
                      border: '1px solid #d9d9d9',
                      borderRadius: '4px',
                      fontSize: '14px'
                    }}
                    required
                  />
                  <button
                    type="button"
                    onClick={countdown === 0 ? generateCaptcha : undefined}
                    disabled={countdown > 0}
                    style={{
                      padding: '8px 16px',
                      backgroundColor: countdown === 0 ? '#2d6aff' : '#f5f5f5',
                      color: countdown === 0 ? 'white' : '#666',
                      borderRadius: '4px',
                      cursor: countdown === 0 ? 'pointer' : 'not-allowed',
                      border: 'none',
                      minWidth: '120px',
                      textAlign: 'center',
                      userSelect: 'none',
                      opacity: countdown > 0 ? 0.6 : 1,
                      fontSize: '14px'
                    }}
                  >
                    {countdown > 0 ? `${countdown}s后重新获取` : '获取验证码'}
                  </button>
                </div>
              </div>

              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
                <label style={{ display: 'flex', alignItems: 'center', cursor: 'pointer', fontSize: '14px', color: '#666' }}>
                  <input
                    type="checkbox"
                    checked={rememberMe}
                    onChange={(e) => setRememberMe(e.target.checked)}
                    style={{ marginRight: '6px', cursor: 'pointer' }}
                  />
                  记住密码
                </label>
                <button
                  type="button"
                  onClick={handleForgotPassword}
                  style={{
                    background: 'none',
                    border: 'none',
                    color: '#2d6aff',
                    fontSize: '14px',
                    cursor: 'pointer',
                    padding: '0',
                    textDecoration: 'underline'
                  }}
                >
                  忘记密码？
                </button>
              </div>

              <button
                type="submit"
                disabled={loading}
                style={{
                  width: '100%',
                  padding: '12px',
                  backgroundColor: loading ? '#91d5ff' : '#2d6aff',
                  color: 'white',
                  border: 'none',
                  borderRadius: '8px',
                  fontSize: '16px',
                  fontWeight: '600',
                  cursor: loading ? 'not-allowed' : 'pointer',
                  opacity: loading ? 0.7 : 1,
                  transition: 'all 0.3s ease',
                  marginTop: '0px'
                }}
              >
                {loading ? '登录中...' : '登录'}
              </button>
            </form>

            <div style={{ marginTop: '15px', textAlign: 'center' }}>
              <span style={{ fontSize: '14px', color: '#666' }}>如果没有账号，请 </span>
              <button
                type="button"
                onClick={handleRegister}
                style={{
                  background: 'none',
                  border: 'none',
                  color: '#2d6aff',
                  fontSize: '14px',
                  cursor: 'pointer',
                  padding: '0',
                  textDecoration: 'underline'
                }}
              >
                注册账号
              </button>
            </div>

            <div style={{ marginTop: '20px', textAlign: 'center', fontSize: '14px', color: '#666' }}>
              <p style={{ margin: '5px 0' }}>测试账号：admin / 123456</p>
              <p style={{ margin: '5px 0' }}>测试账号：test / 123456</p>
            </div>
          </>
        )}

        {/* 验证码弹窗 */}
          {showCaptchaModal && (
            <div
              style={{
                position: 'fixed',
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                backgroundColor: 'rgba(0, 0, 0, 0.6)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                zIndex: 1000,
                backdropFilter: 'blur(4px)'
              }}
              onClick={() => setShowCaptchaModal(false)}
            >
              <div
                style={{
                  backgroundColor: 'white',
                  padding: '30px',
                  borderRadius: '12px',
                  boxShadow: '0 10px 40px rgba(0, 0, 0, 0.3)',
                  textAlign: 'center',
                  minWidth: '300px',
                  maxWidth: '90%',
                  animation: 'fadeIn 0.3s ease-out'
                }}
                onClick={(e) => e.stopPropagation()}
              >
                <h3 style={{ marginBottom: '20px', color: '#2d6aff' }}>请输入验证码</h3>
                <div
                  style={{
                    fontSize: '24px',
                    fontWeight: 'bold',
                    margin: '20px 0',
                    padding: '15px',
                    backgroundColor: '#f5f7fa',
                    borderRadius: '8px',
                    cursor: 'pointer',
                    color: '#2d6aff',
                    letterSpacing: '10px',
                    userSelect: 'text',
                    border: '1px solid #e8e8e8',
                    transition: 'all 0.2s ease'
                  }}
                  onClick={(e) => {
                    e.stopPropagation();
                    navigator.clipboard.writeText(captchaText)
                      .then(() => {
                        alert('验证码已复制到剪贴板');
                      })
                      .catch(err => {
                        console.error('复制失败:', err);
                      });
                  }}
                  title="点击复制验证码"
                >
                  {captchaText}
                </div>
                <div style={{ display: 'flex', gap: '10px', justifyContent: 'center', marginTop: '20px' }}>
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      navigator.clipboard.writeText(captchaText)
                        .then(() => {
                          alert('验证码已复制到剪贴板');
                        })
                        .catch(err => {
                          console.error('复制失败:', err);
                        });
                    }}
                    style={{
                      padding: '10px 20px',
                      backgroundColor: '#4CAF50',
                      color: 'white',
                      border: 'none',
                      borderRadius: '6px',
                      cursor: 'pointer',
                      fontSize: '14px',
                      transition: 'background-color 0.2s ease',
                      fontWeight: '500'
                    }}
                    title="复制验证码到剪贴板"
                  >
                    复制验证码
                  </button>
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      setShowCaptchaModal(false);
                    }}
                    style={{
                      padding: '10px 20px',
                      backgroundColor: '#2d6aff',
                      color: 'white',
                      border: 'none',
                      borderRadius: '6px',
                      cursor: 'pointer',
                      fontSize: '14px',
                      transition: 'background-color 0.2s ease',
                      fontWeight: '500'
                    }}
                  >
                    关闭弹窗
                  </button>
                </div>
              </div>
            </div>
          )}
          
          {/* 忘记密码验证码弹窗 */}
          {showForgotCaptchaModal && (
            <div
              style={{
                position: 'fixed',
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                backgroundColor: 'rgba(0, 0, 0, 0.6)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                zIndex: 1000,
                backdropFilter: 'blur(4px)'
              }}
              onClick={() => setShowForgotCaptchaModal(false)}
            >
              <div
                style={{
                  backgroundColor: 'white',
                  padding: '30px',
                  borderRadius: '12px',
                  boxShadow: '0 10px 40px rgba(0, 0, 0, 0.3)',
                  textAlign: 'center',
                  minWidth: '300px',
                  maxWidth: '90%',
                  animation: 'fadeIn 0.3s ease-out'
                }}
                onClick={(e) => e.stopPropagation()}
              >
                <h3 style={{ marginBottom: '20px', color: '#2d6aff' }}>请输入验证码</h3>
                <div
                  style={{
                    fontSize: '24px',
                    fontWeight: 'bold',
                    margin: '20px 0',
                    padding: '15px',
                    backgroundColor: '#f5f7fa',
                    borderRadius: '8px',
                    cursor: 'pointer',
                    color: '#2d6aff',
                    letterSpacing: '10px',
                    userSelect: 'text',
                    border: '1px solid #e8e8e8',
                    transition: 'all 0.2s ease'
                  }}
                  onClick={(e) => {
                    e.stopPropagation();
                    navigator.clipboard.writeText(forgotCaptchaText)
                      .then(() => {
                        alert('验证码已复制到剪贴板');
                      })
                      .catch(err => {
                        console.error('复制失败:', err);
                      });
                  }}
                  title="点击复制验证码"
                >
                  {forgotCaptchaText}
                </div>
                <div style={{ display: 'flex', gap: '10px', justifyContent: 'center', marginTop: '20px' }}>
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      navigator.clipboard.writeText(forgotCaptchaText)
                        .then(() => {
                          alert('验证码已复制到剪贴板');
                        })
                        .catch(err => {
                          console.error('复制失败:', err);
                        });
                    }}
                    style={{
                      padding: '10px 20px',
                      backgroundColor: '#4CAF50',
                      color: 'white',
                      border: 'none',
                      borderRadius: '6px',
                      cursor: 'pointer',
                      fontSize: '14px',
                      transition: 'background-color 0.2s ease',
                      fontWeight: '500'
                    }}
                    title="复制验证码到剪贴板"
                  >
                    复制验证码
                  </button>
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      setShowForgotCaptchaModal(false);
                    }}
                    style={{
                      padding: '10px 20px',
                      backgroundColor: '#2d6aff',
                      color: 'white',
                      border: 'none',
                      borderRadius: '6px',
                      cursor: 'pointer',
                      fontSize: '14px',
                      transition: 'background-color 0.2s ease',
                      fontWeight: '500'
                    }}
                  >
                    关闭弹窗
                  </button>
                </div>
              </div>
            </div>
          )}
          
          {/* 注册验证码弹窗 */}
          {registerShowCaptchaModal && (
            <div
              style={{
                position: 'fixed',
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                backgroundColor: 'rgba(0, 0, 0, 0.6)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                zIndex: 1000,
                backdropFilter: 'blur(4px)'
              }}
              onClick={() => setRegisterShowCaptchaModal(false)}
            >
              <div
                style={{
                  backgroundColor: 'white',
                  padding: '30px',
                  borderRadius: '12px',
                  boxShadow: '0 10px 40px rgba(0, 0, 0, 0.3)',
                  textAlign: 'center',
                  minWidth: '300px',
                  maxWidth: '90%',
                  animation: 'fadeIn 0.3s ease-out'
                }}
                onClick={(e) => e.stopPropagation()}
              >
                <h3 style={{ marginBottom: '20px', color: '#2d6aff' }}>请输入验证码</h3>
                <div
                  style={{
                    fontSize: '24px',
                    fontWeight: 'bold',
                    margin: '20px 0',
                    padding: '15px',
                    backgroundColor: '#f5f7fa',
                    borderRadius: '8px',
                    cursor: 'pointer',
                    color: '#2d6aff',
                    letterSpacing: '10px',
                    userSelect: 'text',
                    border: '1px solid #e8e8e8',
                    transition: 'all 0.2s ease'
                  }}
                  onClick={(e) => {
                    e.stopPropagation();
                    navigator.clipboard.writeText(registerCaptchaText)
                      .then(() => {
                        alert('验证码已复制到剪贴板');
                      })
                      .catch(err => {
                        console.error('复制失败:', err);
                      });
                  }}
                  title="点击复制验证码"
                >
                  {registerCaptchaText}
                </div>
                <div style={{ display: 'flex', gap: '10px', justifyContent: 'center', marginTop: '20px' }}>
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      navigator.clipboard.writeText(registerCaptchaText)
                        .then(() => {
                          alert('验证码已复制到剪贴板');
                        })
                        .catch(err => {
                          console.error('复制失败:', err);
                        });
                    }}
                    style={{
                      padding: '10px 20px',
                      backgroundColor: '#4CAF50',
                      color: 'white',
                      border: 'none',
                      borderRadius: '6px',
                      cursor: 'pointer',
                      fontSize: '14px',
                      transition: 'background-color 0.2s ease',
                      fontWeight: '500'
                    }}
                    title="复制验证码到剪贴板"
                  >
                    复制验证码
                  </button>
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      setRegisterShowCaptchaModal(false);
                    }}
                    style={{
                      padding: '10px 20px',
                      backgroundColor: '#2d6aff',
                      color: 'white',
                      border: 'none',
                      borderRadius: '6px',
                      cursor: 'pointer',
                      fontSize: '14px',
                      transition: 'background-color 0.2s ease',
                      fontWeight: '500'
                    }}
                  >
                    关闭弹窗
                  </button>
                </div>
              </div>
            </div>
          )}
      </div>
    </div>
  );
};

export default LoginPage;